package com.mojo.netty;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 基于socket的服务-每次请求创建线程
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2021, 广州九尾信息科技有限公司
 * @date 2021/8/26 11:14
 */
public class SocketServer02 {
//    RPS: 1037.3 (requests/second)
//    Max: 163ms
//    Min: 19ms
//    Avg: 27.8ms
//
//  50%   below 23ms
//  60%   below 26ms
//  70%   below 30ms
//  80%   below 35ms
//  90%   below 41ms
//  95%   below 47ms
//  98%   below 55ms
//  99%   below 63ms
//99.9%   below 103ms
    public static void main(String[] args) throws IOException {
        final ServerSocket serverSocket = new ServerSocket(8802);
        while (true) {
            try {
                final Socket accept = serverSocket.accept();
                //线程池处理accept
                new Thread(() -> service(accept)).start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void service(Socket accept) {
        try (OutputStream out = accept.getOutputStream();
             PrintWriter writer = new PrintWriter(out, true);) {
            Thread.sleep(20);
            writer.println("HTTP1.1 200 OK");
            writer.println("ContentType:text/html;charset=utf-8");
            writer.println();
            writer.println("hello socket server");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
